/**   
 *    
 * 项目名称：SmartKungFu   
 * 类名称：OnlineCourseController   
 * 类描述：   在线课程
 * 创建人：zhangl  
 * 创建时间：2016年10月12日 上午10:31:33   
 * 修改人：zhangl   
 * 修改时间：2016年10月12日 上午10:31:33   
 * 修改备注：   
 * @version    
 *    
 */
package com.lst.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.github.miemiedev.mybatis.paginator.domain.PageBounds;
import com.github.miemiedev.mybatis.paginator.domain.PageList;
import com.github.miemiedev.mybatis.paginator.domain.Paginator;
import com.lst.common.BaseController;
import com.lst.common.CommonEnum;
import com.lst.exception.MyException;
import com.lst.model.FolPara;
import com.lst.model.MstButton;
import com.lst.model.MstUser;
import com.lst.model.OnlineCourse;
import com.lst.model.Resources;
import com.lst.service.MstButtonService;
import com.lst.service.OnlineCourseService;
import com.lst.service.ResourcesService;
import com.lst.utils.CommonUtils;
import com.lst.utils.DateUtil;

/**
 * @ClassName: OnlineCourseController
 * @Description:在线课程
 * @author zhangl
 * @date 2016年10月12日 上午10:31:33
 * 
 */
@Controller
@RequestMapping("onlineCourseController")
public class OnlineCourseController extends BaseController {

	@Autowired
	private OnlineCourseService onlineCourseService;

	@Autowired
	private MstButtonService mstButtonService;

	@Autowired
	private ResourcesService resourcesService;

	/**
	 * 
	 * @Title: list
	 * @Description:页面加载
	 * @param @param request
	 * @param @param response
	 * @param @param menuId
	 * @param @param page
	 * @param @param rows
	 * @param @param index_exp
	 * @param @param index_che
	 * @param @param rolName
	 * @param @return
	 * @param @throws MyException 设定文件
	 * @return ModelAndView 返回类型
	 */
	@RequestMapping(value = "/list")
	public ModelAndView list(
			HttpServletRequest request,
			HttpServletResponse response,
			@RequestParam(required = true) int menuId,
			@RequestParam(required = false, defaultValue = CommonEnum.SYSTEMPAGE_PAGE) int page,
			@RequestParam(required = false, defaultValue = CommonEnum.SYSTEMPAGE_PAGESIZE) int rows,
			@RequestParam(required = false, defaultValue = CommonEnum.MENU_STYLE_INDEX_EXP) String index_exp,
			@RequestParam(required = false, defaultValue = CommonEnum.MENU_STYLE_INDEX_CHE) String index_che,
			@RequestParam(required = false, defaultValue = "") String rolName)
					throws MyException {
		Date startDate = new Date();
		logger.info("list begin: " + startDate);

		FolPara folPara = new FolPara();
		folPara.setMenuId(menuId);
		folPara.setPage(page);
		folPara.setRows(rows);
		folPara.setRolName(rolName);

		MstUser mstUser = this.getMySession().getMstUser();
		List<MstButton> btns = CommonUtils.readPermissionWithBtn(menuId,
				mstUser, mstButtonService);

		ModelAndView mv = new ModelAndView(CommonEnum.FORWARD_VIEW_MAIN_KUNGFU + "oc_list");
		mv.addObject("btns", btns);
		mv.addObject("folPara", folPara);

		mv.addObject("MENU_STYLE_INDEX_EXP", index_exp);
		mv.addObject("MENU_STYLE_INDEX_CHE", index_che);

		logger.info("list end run(s): " + DateUtil.calLastedTime(startDate));

		return mv;
	}

	/**
	 * 
	 * @Title: queryList
	 * @Description: 查询数据集
	 * @param @param page
	 * @param @param rows
	 * @param @param sort
	 * @param @param order
	 * @param @param title
	 * @param @return
	 * @param @throws MyException    设定文件
	 * @return Object    返回类型
	 */
	@RequestMapping(value = "/queryList")
	@ResponseBody
	public Object queryList(
			@RequestParam(required = false, defaultValue = CommonEnum.SYSTEMPAGE_PAGE) Integer page,
			@RequestParam(required = false, defaultValue = CommonEnum.SYSTEMPAGE_PAGESIZE) Integer rows,
			@RequestParam(required = false, defaultValue = "") String sort,
			@RequestParam(required = false, defaultValue = CommonEnum.SYSTEM_ORDER_DESC) String order,
			@RequestParam(required = false, defaultValue = "") String title)
					throws MyException {
		Date startDate = new Date();
		logger.info("queryList begin: " + startDate);

		Map<String, Object> reqMap = new HashMap<String, Object>();
		reqMap.put("isDeleted", 0);
		reqMap.put("enabled", 1);
		
		if(!StringUtils.isEmpty(title)){
			reqMap.put("_title", title);
		}

		PageBounds pageBounds = new PageBounds(page, rows);
		List<OnlineCourse> list = onlineCourseService.queryByList(reqMap,pageBounds);
		
		for(OnlineCourse oc : list){
			oc.setDescript(CommonUtils.formatStr(oc.getDescript(), "● ", "\r\n"));
			oc.setIntroduction(CommonUtils.formatStr(oc.getIntroduction(), "● ", "\r\n"));
			oc.setCycle(CommonUtils.formatStr(oc.getCycle(), "● ", "\r\n"));
			oc.setNotice(CommonUtils.formatStr(oc.getNotice(), "● ", "\r\n"));
			oc.setPeople(CommonUtils.formatStr(oc.getPeople(), "● ", "\r\n"));
			oc.setActionname(CommonUtils.formatStr(oc.getActionname(), "● ", "\r\n"));
			oc.setReserved10(CommonUtils.formatStr(oc.getReserved10(), "● ", "\r\n"));
			oc.setReserved9(CommonUtils.formatStr(oc.getReserved9(), "● ", "\r\n"));
		}
		
		PageList<OnlineCourse> pageList = (PageList<OnlineCourse>) list;
		Paginator paginator = pageList.getPaginator();

		HashMap<String, Object> indexPages = new HashMap<String, Object>();
		indexPages.put("total", paginator.getTotalCount());
		indexPages.put("rows", list);

		logger.info("queryList end run(s): "
				+ DateUtil.calLastedTime(startDate));

		return indexPages;
	}

	/**
	 * 
	 * @Title: edit
	 * @Description:编辑页面
	 * @param @param id
	 * @param @param index_exp
	 * @param @param index_che
	 * @param @return 设定文件
	 * @return ModelAndView 返回类型
	 */
	@RequestMapping(value = "/edit")
	public ModelAndView edit(
			@RequestParam(required = false) String id,
			@RequestParam(required = false, defaultValue = CommonEnum.MENU_STYLE_INDEX_EXP) String index_exp,
			@RequestParam(required = false, defaultValue = CommonEnum.MENU_STYLE_INDEX_CHE) String index_che) {
		Date startDate = new Date();
		logger.info("edit begin: " + startDate);

		ModelAndView mv = new ModelAndView(CommonEnum.FORWARD_VIEW_MAIN_KUNGFU
				+ "oc_edit");

		if (!StringUtils.isBlank(id)) {
			OnlineCourse onlineCourse = onlineCourseService
					.selectByPrimaryKey(Integer.parseInt(id));
			mv.addObject("onlineCourse", onlineCourse);
		}

		mv.addObject("MENU_STYLE_INDEX_EXP", index_exp);
		mv.addObject("MENU_STYLE_INDEX_CHE", index_che);

		logger.info("edit end run(s): " + DateUtil.calLastedTime(startDate));

		return mv;
	}

	/**
	 * 
	 * @Title: save
	 * @Description:save
	 * @param @param mstrole
	 * @param @param folPara
	 * @param @return
	 * @param @throws MyException 设定文件
	 * @return String 返回类型
	 */
	@RequestMapping(value = "/save", method = RequestMethod.POST)
	public String save(OnlineCourse onlineCourse, FolPara folPara,HttpServletRequest request,String [] videoname,String [] reserved12,String [] imagename) throws MyException {
		Date startDate = new Date();
		logger.info("save begin: " + startDate);

		MstUser mstUser = this.getMySession().getMstUser();

		if (onlineCourse.getId() != null) {
			onlineCourse.setUpdatedate(startDate);
			onlineCourse.setUpdateuser(mstUser.getId());
			
//			if(!CommonEnum.SYSCODE_ONLINECOURSETYPE_QINGGONG.equals(onlineCourse.getType()) ){
//				onlineCourse.setReserved1(null);
//			}

			onlineCourseService.updateByPrimaryKeySelective(onlineCourse);
		} else {
			onlineCourse.setEnabled(true);
			onlineCourse.setIsdeleted(false);
			onlineCourse.setCreatedate(startDate);
			onlineCourse.setUpdatedate(startDate);
			onlineCourse.setCreateuser(mstUser.getId());
			
//			if(!CommonEnum.SYSCODE_ONLINECOURSETYPE_QINGGONG.equals(onlineCourse.getType()) ){
//				onlineCourse.setReserved1(null);
//			}

			onlineCourseService.insert(onlineCourse);
		}

		//视频资源信息维护
		try {

			if(videoname != null && videoname.length != 0){
				Map<String, String> resMap = new HashMap<String,String>();
				resMap.put("userId", mstUser.getId().toString());
				resMap.put("ownerId", onlineCourse.getId().toString());
				resMap.put("tableName", "ONLINE_COURSE");

				Map<String, Object> dataMap = CommonUtils.getResourcesData(request, videoname, resMap,CommonEnum.SYSCODE_REOURCES_TYPE_IMAGE,false);
				@SuppressWarnings("unchecked")
				List<Resources> resources = (List<Resources>) dataMap.get("resources");
				resourcesService.saveList(resources);

				//将所有图片获取出来
				String imagePath = "";
				for(Resources resource : resources){
					imagePath += resource.getRespath() + resource.getResname() + ";";
				}

				OnlineCourse imgVi = new OnlineCourse();
				imgVi.setUpdatedate(startDate);
				imgVi.setUpdateuser(mstUser.getId());
				imgVi.setId(onlineCourse.getId());
				imgVi.setCoverurl(imagePath.substring(0 , imagePath.length() - 1));
				onlineCourseService.updateByPrimaryKeySelective(imgVi);
			}
			
			if(reserved12 != null && reserved12.length != 0){
				Map<String, String> resMap = new HashMap<String,String>();
				resMap.put("userId", mstUser.getId().toString());
				resMap.put("ownerId", onlineCourse.getId().toString());
				resMap.put("tableName", "ONLINE_COURSE");

				Map<String, Object> dataMap = CommonUtils.getResourcesData(request, reserved12, resMap,CommonEnum.SYSCODE_REOURCES_TYPE_IMAGE,false);
				@SuppressWarnings("unchecked")
				List<Resources> resources = (List<Resources>) dataMap.get("resources");
				
				resourcesService.saveList(resources);

				//将所有图片获取出来
				String imagePath = "";
				for(Resources resource : resources){
					imagePath += resource.getRespath() + resource.getResname() + ";";
				}

				OnlineCourse imgVi = new OnlineCourse();
				imgVi.setUpdatedate(startDate);
				imgVi.setUpdateuser(mstUser.getId());
				imgVi.setId(onlineCourse.getId());
				imgVi.setReserved12(imagePath.substring(0 , imagePath.length() - 1));

				onlineCourseService.updateByPrimaryKeySelective(imgVi);
			}
			
			if(imagename != null && imagename.length != 0){
				Map<String, String> resMap = new HashMap<String,String>();
				resMap.put("userId", mstUser.getId().toString());
				resMap.put("ownerId", onlineCourse.getId().toString());
				resMap.put("tableName", "ONLINE_COURSE");

				Map<String, Object> dataMap = CommonUtils.getResourcesData(request, imagename, resMap,CommonEnum.SYSCODE_REOURCES_TYPE_IMAGE,false);
				
				@SuppressWarnings("unchecked")
				List<Resources> resources = (List<Resources>) dataMap.get("resources");
				
				resourcesService.saveList(resources);

				//将所有图片获取出来
				String imagePath = "";
				for(Resources resource : resources){
					imagePath += resource.getRespath() + resource.getResname() + ";";
				}

				OnlineCourse imgVi = new OnlineCourse();
				imgVi.setUpdatedate(startDate);
				imgVi.setUpdateuser(mstUser.getId());
				imgVi.setId(onlineCourse.getId());
				imgVi.setRemark(imagePath.substring(0 , imagePath.length() - 1));;

				onlineCourseService.updateByPrimaryKeySelective(imgVi);
			}
			
		} catch (Exception e) {
			logger.error("save error: " ,e);
		}

		StringBuffer sb = new StringBuffer("?");
		sb.append("menuId=" + folPara.getMenuId());
		sb.append("&page=" + folPara.getPage());
		sb.append("&rows=" + folPara.getRows());
		sb.append("&titleFol=" + folPara.getTitleFol());
		
		sb.append("&index_exp=" + folPara.getIndex_exp());
		sb.append("&index_che=" + folPara.getIndex_che());

		logger.info("save end run(s):" + DateUtil.calLastedTime(startDate));

		return "redirect:list" + sb.toString();
	}

	/**
	 * 
	 * @Title: delList
	 * @Description: 批量删除
	 * @param @param request
	 * @param @param response
	 * @param @param ids
	 * @param @return
	 * @param @throws MyException 设定文件
	 * @return boolean 返回类型
	 */
	@RequestMapping("delList")
	@ResponseBody
	public boolean delList(HttpServletRequest request,
			HttpServletResponse response,
			@RequestParam(required = true) String ids) throws MyException {
		Date startDate = new Date();
		logger.info("delList begin: " + startDate);

		boolean flag = false;

		MstUser mstUser = this.getMySession().getMstUser();

		Map<String, Object> reqMap = new HashMap<String, Object>();
		reqMap.put("ids", ids);
		reqMap.put("updateUser", mstUser.getId());

		try {
			onlineCourseService.delList(reqMap);
			flag = true;
		} catch (Exception e) {
			logger.error("delList error: ", e);
		}

		logger.info("delList end run(s): " + DateUtil.calLastedTime(startDate));

		return flag;
	}
}
